package com.kbt.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.*;
import android.widget.*;
import com.google.gson.Gson;
import com.kbt.adapter.GoodForOrderItemAdapter;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.model.data.*;
import com.kbt.model.holder.OrderInfoHolder;
import com.kbt.net.RequestManager;
import com.kbt.util.data.StaticData;
import com.kbt.util.photo.Bimp;
import com.kbt.util.photo.FileUtils;
import com.kbt.util.photo.ImageItem;
import com.kbt.util.photo.PublicWay;
import com.kbt.util.tool.RestListViewSizeTool;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import com.kbt.util.utils.LoadingDialog;
import com.kbt.util.utils.UpLoadImage;
import com.kbt.util.utils.Utils;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Message;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;


import android.os.Handler;

import javax.sql.RowSetListener;


/**
 * @Title: KBT_ANDRIOD
 * @Copyright: KJ Co., Ltd. Copyright 2015-2020,  All rights reserved
 * @Description: $打开商品售后信息的Activity
 * @author: zhgk
 * @data: 2015/8/21 13:37
 * @version: V1.0
 */
public class AfterServiceActivity extends Activity implements RequestManager.ResponseInterface {
    private static final int TAKE_PHOTO = 11001;
    private static final int CHOSE_PHOTO = 11002;
    private static List<ImageView> imgViewList = new ArrayList<ImageView>();
    private String imageDir;
    private OrderBean orderInfo;
    private OrderInfoHolder itemHolder;
    private RequestManager mRequestManager;
    private Map<String, String> map = null;

    //上传照片
    private GridView noScrollgridview;
    private GridAdapter adapter;
    public static Bitmap bimap;

    private Bundle bl;
    private TextView submit;

    //盛放图片id
    private List<String> groupIdList;

    private EditText order_qksm;
    private RadioGroup radio_group;
    private RadioButton good_bf;
    private RadioButton good_hh;
    private RadioButton good_tk;
    //申请类型
    private String apply_type = "1";
    private BaseBean baseBean;
    private String state;
    private LoadingDialog mProgress;


    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.after_service);
        this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_return_btn);

        //设置返回按钮事件,关闭当前Activity，返回数据
        ImageView returnImg = (ImageView) findViewById(R.id.return_btn);
        returnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApplication.getInstance().qingKuang = "";
                Bimp.tempSelectBitmap.clear();
                //地址不变，保留原来地址
                setResult(RESULT_CANCELED, null);
                BaseApplication.getInstance().removeActivity(AfterServiceActivity.this);
                BaseApplication.getInstance().apply_type="1";
                finish();
            }
        });

        TextView appTitleView = (TextView) findViewById(R.id.center_title);
        submit = (TextView) findViewById(R.id.submit);
        submit.setVisibility(View.VISIBLE);
        appTitleView.setSelected(false);
        appTitleView.setText("售后服务");
        //获取订单数据
        initOrderInfoData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        BaseApplication.getInstance().addActivity(AfterServiceActivity.this);
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        map = new HashMap<String, String>();

        order_qksm = (EditText) findViewById(R.id.order_qksm);
        radio_group = (RadioGroup) findViewById(R.id.radio_group);
        order_qksm.setText(BaseApplication.getInstance().qingKuang);
        good_tk = (RadioButton) findViewById(R.id.good_tk);
        good_hh = (RadioButton) findViewById(R.id.good_hh);
        good_bf = (RadioButton) findViewById(R.id.good_bf);
        if(BaseApplication.getInstance().apply_type.equals("1")){
            good_bf.setChecked(true);
            good_hh.setChecked(false);
            good_tk.setChecked(false);
        }else if(BaseApplication.getInstance().apply_type.equals("2")){
            good_bf.setChecked(false);
            good_hh.setChecked(true);
            good_tk.setChecked(false);
        }else if(BaseApplication.getInstance().apply_type.equals("3")){
            good_bf.setChecked(false);
            good_hh.setChecked(false);
            good_tk.setChecked(true);
        }

        initOrderView();
        initReturnView();
        setListener();
    }

    private void initReturnView() {
        noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
        // 定制点击GridView 的时候出现的背景色，这儿设置无背景色
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter = new GridAdapter(this);
        // 开一个线程，一直在检测最大图片数量是否达到最大值 为何要开一个线程 ???
        adapter.update();
        noScrollgridview.setAdapter(adapter);
        itemHolder = new OrderInfoHolder();
        itemHolder.setOrderNoView((TextView) findViewById(R.id.orderNo));
        itemHolder.setOrderCreateTimeView((TextView) findViewById(R.id.createTime));

        itemHolder.setGoodListView((ListView) findViewById(R.id.goodListForOrder));

        itemHolder.setOrderStatus((TextView) findViewById(R.id.orderStatus));

        itemHolder.setOrderCount((TextView) findViewById(R.id.orderCount));
        itemHolder.setOrderFee((TextView) findViewById(R.id.totalFeel));
        itemHolder.getOrderNoView().setText("订单号：" + orderInfo.getOrder_no());

        itemHolder.getOrderCreateTimeView().setText(orderInfo.getOrder_create_time());
        //订单商品列表
        List<OrderGoodsListBean> goodList = orderInfo.getGoods_list();
        GoodForOrderItemAdapter itemAdapter = new GoodForOrderItemAdapter(this, goodList);
        itemHolder.getGoodListView().setAdapter(itemAdapter);
        RestListViewSizeTool.setListViewHeightBasedOnChildren(itemHolder.getGoodListView());


        itemHolder.getOrderStatus().setText("待评价");

        itemHolder.getOrderCount().setText("共计 " + orderInfo.getGoods_count() + " 件");
        itemHolder.getOrderFee().setText(String.valueOf(orderInfo.getOrder_real_je()));

    }

    //监听
    private void setListener() {
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if("".equals(order_qksm.getText().toString())){
                    Toast.makeText(AfterServiceActivity.this, "请填写情况说明!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Bimp.max <=0) {
                    Toast.makeText(AfterServiceActivity.this, "请上传图片!", Toast.LENGTH_SHORT).show();
                    return;
                }
                showProgress();
                groupIdList = new ArrayList<String>();
                groupIdList.clear();
                new Thread() {
                    @Override
                    public void run() {
                        if (Bimp.max > 0) {
                            for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
                                String imagePath = Bimp.tempSelectBitmap.get(i).getImagePath().toString();
                                String groupId = UpLoadImage.formUpload(Constants.ServiceInterFace.upLoadURL, imagePath);
                                if (!"".equals(groupId)) {
                                    groupIdList.add(groupId);
                                } else {
                                    Toast.makeText(AfterServiceActivity.this, "上传失败!", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                            }
                        }
                        //保存售后信息
                        httpSaveShouhou();
                    }
                }.start();
            }
        });
        radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.good_bf) {
                    apply_type = "1";
                    BaseApplication.getInstance().apply_type = "1";
                }
                if (checkedId == R.id.good_hh) {
                    apply_type = "2";
                    BaseApplication.getInstance().apply_type = "2";
                }
                if (checkedId == R.id.good_tk) {
                    apply_type = "3";
                    BaseApplication.getInstance().apply_type = "3";
                }
            }
        });
    }

    //保存售后信息
    private void httpSaveShouhou() {
        String image = "";
        if (!groupIdList.isEmpty()) {
            for (int i = 0; i < groupIdList.size(); i++) {
                image += groupIdList.get(i) + ",";
            }
        }
        if(Utils.isNetworkAvailable(AfterServiceActivity.this)) {
            map.clear();
            map.put("methodType", "updateSh");
            Gson gson = new Gson();
            Map dataMap = new HashMap<String,String>();
            dataMap.put("order_no", orderInfo.getOrder_no());
            dataMap.put("apply_time", new SimpleDateFormat("yyyy-dd-mm HH:MM:ss").format(new Date()));
            dataMap.put("apply_type", BaseApplication.getInstance().apply_type);
            dataMap.put("apply_desc", order_qksm.getText().toString());
            dataMap.put("apply_img", image);
            map.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.saveShouHouURL, map, Constants.RequestTag.saveShouHouTag, BaseBean.class);
        }else{
            Toast.makeText(AfterServiceActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }


    private void initOrderView() {
        Button localBtn = (Button) findViewById(R.id.local_btn);
        localBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApplication.getInstance().qingKuang =order_qksm.getText().toString();
                Intent intent = new Intent(AfterServiceActivity.this, AlbumActivity.class);
                intent.putExtra("bundle", bl);
                intent.putExtra("state",state);
                startActivity(intent);
                // activity跳转动画
                overridePendingTransition(R.anim.activity_translate_in,
                        R.anim.activity_translate_out);
                finish();
            }
        });

        Button carBtn = (Button) findViewById(R.id.carm_btn);
        carBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photo();
            }
        });
    }

    /*********
     * 获取订单数据
     */
    private void initOrderInfoData() {
        Intent intent = getIntent();
        state = intent.getStringExtra(StaticData.ORDER_TYPE);
        bl = intent.getBundleExtra("bundle");
        if (bl != null) {
            Object obj = bl.getSerializable("orderInfo");
            orderInfo = obj == null ? new OrderBean() : (OrderBean) obj;
        }
    }

    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        stopProgress();
        if (tag == Constants.RequestTag.saveShouHouTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if (baseBean.getResult().equals("success")) {
                    BaseApplication.getInstance().qingKuang ="";
                    BaseApplication.getInstance().apply_type="1";
                    Bimp.tempSelectBitmap.clear();
                    BaseApplication.getInstance().removeActivity(AfterServiceActivity.this);
                    finish();
                } else {
                    Toast.makeText(AfterServiceActivity.this, "" + baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        stopProgress();
        Toast.makeText(AfterServiceActivity.this, R.string.noWangluo, Toast.LENGTH_SHORT).show();
    }

    // 图片的gridview的adapter
    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private int selectedPosition = -1;
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }

        public int getCount() {
            if (Bimp.tempSelectBitmap.size() == 4) {
                return 4;
            }
            return (Bimp.tempSelectBitmap.size() + 1);
        }

        public Object getItem(int arg0) {
            return null;
        }

        public long getItemId(int arg0) {
            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == Bimp.tempSelectBitmap.size()) {
                // 如果超出4张图片，那么就将添加按钮隐藏掉不允许点击了
                if (position == 4) {
                    Toast.makeText(AfterServiceActivity.this, "只能上传4张", Toast.LENGTH_SHORT).show();
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
            }

            return convertView;
        }

        public class ViewHolder {
            public ImageView image;
        }

        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };

        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.tempSelectBitmap.size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            Bimp.max += 1;
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }
                }
            }).start();
        }
    }

    protected void onRestart() {
        adapter.update();
        super.onRestart();
    }

    private static final int TAKE_PICTURE = 0x000001;

    public void photo() {
        BaseApplication.getInstance().qingKuang =order_qksm.getText().toString();
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (Bimp.tempSelectBitmap.size() < 4 && resultCode == RESULT_OK) {

                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    File path = FileUtils.saveBitmap(bm, fileName);
                    ImageItem takePhoto = new ImageItem();
                    takePhoto.setBitmap(bm);
                    takePhoto.setImagePath(path + "");
                    Bimp.tempSelectBitmap.add(takePhoto);
                }
                break;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            for (int i = 0; i < PublicWay.activityList.size(); i++) {
                if (null != PublicWay.activityList.get(i)) {
                    PublicWay.activityList.get(i).finish();
                }
            }
            Bimp.tempSelectBitmap.clear();
            Bimp.max = 0;
            BaseApplication.getInstance().qingKuang = "";
            BaseApplication.getInstance().apply_type="1";
            BaseApplication.getInstance().removeActivity(AfterServiceActivity.this);
            AfterServiceActivity.this.finish();
        }
        return true;
    }
    /**
     * progressDialog的展示
     */
    public void showProgress() {
        if (mProgress == null) {
            mProgress = new LoadingDialog(AfterServiceActivity.this,"");
            mProgress.setCancelable(true);
            mProgress.show();

        } else {
            if (mProgress.isShowing()) {
                stopProgress();
            } else {
                mProgress.show();
            }
        }
    }


    /**
     * progressDialog的消失
     */
    public void stopProgress() {
        if (mProgress != null) {
            mProgress.dismiss();
            mProgress = null;
        }
    }

}
